package cloud.health.common.file.infrastructure;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.StringJoiner;

@Data
public class R<T> implements Serializable {

    private int code;

    private boolean success;

    private String message;

    private T data;

    public static <E> R success(int code, String message, E data) {
        R r = new R();
        r.code = code;
        r.success = true;
        r.message = message;
        r.data = data;
        return r;
    }

    public static R success() {
        return success(0, "", null);
    }

    public static <E> R success(E data) {
        return success(0, "", data);
    }

    public static R success(int code, String message) {
        return success(code, message, null);
    }

    public static <E> R fail(int code, String message, E data) {
        R r = new R();
        r.code = code;
        r.success = false;
        r.message = message;
        r.data = data;
        return r;
    }

    public static R fail(int code, String message) {
        return fail(code, message, null);
    }

    public byte[] response(String contentType) {
        String s = JSON.toJSONString(this);
        StringJoiner sj = new StringJoiner("\r\n");
        sj.add("HTTP/1.1 200 OK")
                .add("Content-Type: " + (StringUtils.isBlank(contentType) ? "application/json" : contentType))
                .add("Content-Length: " + s.getBytes().length)
                .add("")
                .add(s);
        return sj.toString().getBytes();
    }

    public byte[] response() {
        return response(null);
    }

}
